package com.study.example.gameserver.module.scene.bt.node;

import com.sparrow.common.ai.behaviortree.BehaviorContext;
import com.sparrow.common.ai.behaviortree.node.impl.ConditionNode;
import com.sparrow.common.aoi.util.MapUtil;
import com.study.example.gameserver.module.scene.domain.SceneMap;
import com.study.example.gameserver.module.scene.entity.IPlayerEntity;
import com.study.example.gameserver.module.scene.entity.impl.Monster;

/**
 * 是否敌人在视野范围内
 */
public class IsEnemyVisible extends ConditionNode {

    private static int VISIBLE_DIS = 10;

    @Override
    public boolean check(BehaviorContext context) {
        Monster monster = context.getOwner();
        if (monster == null) {
            return false;
        }
        SceneMap sceneMap = context.get("SceneMap", SceneMap.class);
        if (sceneMap == null) {
            return false;
        }
        if (monster.getTargetId() > 0) {
            IPlayerEntity target = sceneMap.getPlayers().get(monster.getTargetId());
            if (target == null) {
                monster.setTargetId(0);
            } else {
                float distance = MapUtil.getDistance(monster.getPos(), target.getPos());
                if (distance > VISIBLE_DIS) {
                    monster.setTargetId(0);
                }
            }
        }
        if (monster.getTargetId() > 0) {
            return true;
        }
        for (IPlayerEntity p : sceneMap.getPlayers().values()) {
            float distance = MapUtil.getDistance(monster.getPos(), p.getPos());
            if (distance <= VISIBLE_DIS) {
                monster.setTargetId(p.getPlayerId());
                return true;
            }
        }
        return false;
    }

}
